#include "LastLoadedFirstNameResolutor.h"
#include "Plugin.h"

LastLoadedFirstNameResolutor::LastLoadedFirstNameResolutor() : INameResolutor()
{
	descriptorsRepository = DescriptorsRepository::GetInstance();
}

std::string LastLoadedFirstNameResolutor::ResolveTypeName( string type )
{
	if ( regex_match( type, m, regex("(.+)\\.(.+)") ) )
	{
		// if type is a fully qualified name no action is required
		return type;
	}

	BOOST_FOREACH(PluginSp p, plugins)
	{
		string fullyQualifiedType = Utility::GetFullyQualifiedName( p->GetName(), type);
		if ( descriptorsRepository->ExistType( fullyQualifiedType ) )
		{
			return fullyQualifiedType;
		}
	}

	throw SArgumentException("Resolution error of '" + type + "'");
}

std::string LastLoadedFirstNameResolutor::ResolveCommandName( string command )
{
	if ( regex_match( command, m, regex("(.+)\\.(.+)") ) )
	{
		// if command is a fully qualified name no action is required
		return command;
	}

	BOOST_FOREACH(PluginSp p, plugins)
	{
		string fullyQualifiedCommand = Utility::GetFullyQualifiedName( p->GetName(), command);
		if ( descriptorsRepository->ExistCommand( fullyQualifiedCommand ) )
		{
			return fullyQualifiedCommand;
		}
	}

	throw SArgumentException("Resolution error of '" + command + "'");
}

void LastLoadedFirstNameResolutor::AddOrSelectPlugin( PluginSp plugin )
{
	bool pluginFound = false;

	BOOST_FOREACH(PluginSp p, plugins)
	{
		if ( p == plugin )
		{
			pluginFound = true;
		}
	}

	// Implement the logic Last Loaded First
	if ( pluginFound )
	{
		list<PluginSp>::iterator it, removeIt;

		for ( it = plugins.begin(); it != plugins.end(); ++it)
		{
			if ( *it == plugin )
			{
				removeIt = it;
				break;
			}
		}

		plugins.erase(removeIt);

		plugins.push_front(plugin);
	}
	else
	{
		plugins.push_front(plugin);
	}

	return;
}
